import axios from 'axios';

const instance = axios.create({
    baseURL: '',
    timeout: 10000
});

instance.interceptors.request.use(
    config => {
        const accessToken = localStorage.getItem('accessToken');
        if (accessToken) {
            config.headers.Authorization = `Bearer ${accessToken}`;
        }

        // 检查 accessToken 是否即将过期
        const isTokenExpiring = () => {
            const token = localStorage.getItem('accessToken');
            if (!token) return true;
            const decoded = JSON.parse(atob(token.split('.')[1]));
            const currentTime = Math.floor(Date.now() / 1000);
            return decoded.exp - currentTime < 60; // 提前 60 秒刷新
        };

        if (isTokenExpiring()) {
            return refreshToken().then(newAccessToken => {
                localStorage.setItem('accessToken', newAccessToken);
                config.headers.Authorization = `Bearer ${newAccessToken}`;
                return config;
            }).catch(error => {
                // 处理刷新失败的情况，例如清除令牌并跳转到登录页面
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                // 这里假设使用 react-router-dom 进行路由跳转
                // history.push('/login');
                return Promise.reject(error);
            });
        }

        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 刷新令牌的函数
const refreshToken = async () => {
    const refreshToken = localStorage.getItem('refreshToken');
    const response = await instance.post('/refreshToken', { refreshToken });
    return response.data.accessToken;
};

export default instance;